package com.bds.btcdc.web.service;

import com.bds.btcdc.web.utils.GenericSuperClass;
import org.apache.log4j.Logger;
import org.nutz.dao.Cnd;
import org.nutz.dao.impl.NutDao;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by DongChenchen on 2018/5/16 0016
 */
public class BaseService<T> {
    protected Logger logger = org.apache.log4j.Logger.getLogger(getClass());
    //类型转换
    private Class t = GenericSuperClass.getSuperClassGenricType(this.getClass());
    @Resource
    protected NutDao dao;

    /**
     * 根据id查找
     * @param id
     * @return
     */
    public T getOneById(Long id) {
        return (T)dao.fetch(t, Cnd.where("id", "=", id));
    }

    /**
     * 更新多个
     * @param ent
     * @return
     */
    public Boolean updateAll(List<T> ent) {
        return dao.update(ent) == 0?false:true;
    }

    /**
     *  更新或者插入多个
     * @param ent
     * @return
     */
    public Boolean updateOrInsertAll(List<T> ent) {
        Boolean res=true;
        for(T en:ent) {
            Boolean suc=updateOrInsertOne(en);
            if(!suc){
                res=false;
            }
        }
        return res;
    }
    /**
     *  更新或者插入1个
     * @param ent
     * @return
     */
    public Boolean updateOrInsertOne(T ent) {
        Object id = GenericSuperClass.getFieldValue(ent, "id");
        if(id==null){
            return dao.insert(ent) == null ? false : true;
        }else {
            return dao.update(ent) == 0 ? false : true;
        }
    }
    /**
     * 插入1个
     * @param ent
     * @return
     */
    public Boolean insertOne(T ent) {
        return dao.insert(ent)==null?false:true;
    }
    public List<T> getAll(){
        return dao.query(t, null);
    }
    public T createTable(){
        return (T)dao.create(t,false);
    }


}
